<template>
  <div>
    <el-card>
      <el-row>
        <el-col :span="12"><span>环境选择</span></el-col>
        <el-col :span="12">
          <el-select v-model="currentConfigId" @change="setEnvironment">
            <el-option v-for="item in environmentList" :label="item.configName" :key="item.configId"
                       :value="item.configId"></el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row class="row-custom">
        <el-col :span="24">
          <el-input v-model="inputText" type="textarea" placeholder="输入要加密&解密的内容" :rows="10"></el-input>
        </el-col>
      </el-row>
      <el-row class="row-custom">
        <el-col :span="24">
          <el-input v-model="outputText" type="textarea" placeholder="加密&解密结果" :rows="10" readonly></el-input>
        </el-col>
      </el-row>
      <el-row class="row-custom">
        <el-col :span="24">
          <el-button type="success" @click="getClipboardData">一键粘贴</el-button>
          <el-button type="info" @click="clearVal">清除</el-button>
          <el-button type="primary" @click="reqEncrypt">请求加密</el-button>
          <el-button type="success" @click="reqDecrypt">请求解密</el-button>
          <el-button type="primary" @click="resDecrypt">响应解密</el-button>
          <el-button type="danger" @click="copyResult">复制结果</el-button>
          <el-button type="danger" @click="doSigned">加密结果加签</el-button>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>
<script setup>
import {ref} from 'vue';
import {onMounted} from 'vue';
import {doEncrypt, doDecrypt, sha256} from "@/utils/crypto.js";
import {getAllConfigList} from "@/api/encryption/envconfig.js";
import {ElMessage} from 'element-plus'

const environment = ref();
const inputText = ref('');
const outputText = ref('');

const environmentList = ref([])
const currentConfigId = ref(null)

onMounted(async () => {
  await getAllConfigList().then(res => {
    environmentList.value = res.rows
    if (environmentList.value) {
      environment.value = environmentList.value[0]
      currentConfigId.value = environmentList.value[0].configId
    }
  })
});

const setEnvironment = (val) => {
  environment.value = environmentList.value.find(item => item.configId === val)
  ElMessage({
    message: '当前环境已切换为' + environment.value.configName,
    type: 'success',
  })
};

//请求加密
const reqEncrypt = () => {
  if (environment.value) {
    if (inputText.value.length > 0) {
      outputText.value = doEncrypt(inputText.value, environment.value.requestPublicKey)
    } else {
      ElMessage({
        message: '加密内容为空',
        type: 'error',
      })
    }
  } else {
    ElMessage({
      message: '请选择环境',
      type: 'error',
    })
  }

};

//请求解密
const reqDecrypt = () => {
  try {
    if (environment.value) {
      let inputData = inputText.value;
      if (inputData.length > 0) {
        if (inputData.startsWith('{') && inputData.endsWith('}')) {
          let parse = JSON.parse(inputData);
          inputData = parse['encryptData']
        }
        outputText.value = doDecrypt(inputData, environment.value.requestPrivateKey)
      } else {
        ElMessage({
          message: '解密内容为空',
          type: 'error',
        })
      }
    } else {
      ElMessage({
        message: '请选择环境',
        type: 'error',
      })
    }
  } catch (e) {
    ElMessage({
      message: e.message,
      type: 'error',
    })
  }
};

//响应解密
const resDecrypt = () => {
  try {
    if (environment.value) {
      let inputData = inputText.value;
      if (inputData.length > 0) {
        if (inputData.startsWith('{') && inputData.endsWith('}')) {
          let parse = JSON.parse(inputData);
          inputData = parse['encryptData']
        }
        outputText.value = doDecrypt(inputData, environment.value.responsePrivateKey)
      } else {
        ElMessage({
          message: '解密内容为空',
          type: 'error',
        })
      }
    } else {
      ElMessage({
        message: '请选择环境',
        type: 'error',
      })
    }
  } catch (e) {
    ElMessage({
      message: e.message,
      type: 'error',
    })
  }
};

const doSigned = () => {
  if (outputText.value) {
    copy2Clipboard(sha256(outputText.value))
  }
}

const copyResult = () => {
  if (outputText.value) {
    copy2Clipboard(outputText.value)
  }
}

const copy2Clipboard = (data) => {
  if (!data) {
    ElMessage({
      message: '数据为空，无法复制',
      type: 'warning',
    })
    return
  }
  navigator.clipboard.writeText(data)
      .then(() => {
        ElMessage({
          message: '文本已复制到剪贴板',
          type: 'success',
        })
      })
      .catch(err => {
        // 复制失败后的操作
        console.error('复制失败:', err);
        ElMessage({
          message: '复制失败',
          type: 'error',
        })
      });
}

const getClipboardData = async () => {
  try {
    const text = await navigator.clipboard.readText();
    inputText.value = text
  } catch (err) {
    console.error("无法读取剪贴板内容: ", err);
    ElMessage({
      message: '无法读取剪贴板内容',
      type: 'error',
    })
  }
}

const clearVal = () => {
  inputText.value = ''
  outputText.value = ''
}
</script>


<style scoped>
.row-custom {
  margin-top: 20px;
}
</style>
